<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[5px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="土地名称" prop="lanName">
              <el-input v-model="queryParams.lanName" placeholder="请输入土地名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="宗地编号" prop="parcelCode">
              <el-input v-model="queryParams.parcelCode" placeholder="请输入宗地编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="受让单位" prop="transferee">
              <el-input v-model="queryParams.transferee" placeholder="请输入受让单位" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="土地用途" prop="landuse">
              <el-select v-model="queryParams.landuse" placeholder="请选择土地用途" clearable>
                <el-option v-for="dict in land_use" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="抵押状态" prop="collateralStatus">
              <el-select v-model="queryParams.collateralStatus" placeholder="请选择抵押状态" clearable>
                <el-option v-for="dict in land_collateral_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div style="text-align: right">
          <el-button type="warning" icon="Download" @click="handleExport">导出 </el-button>
          <el-button plain icon="Plus" @click="handleOpen('create')">新增 </el-button>
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除 </el-button>
        </div>
      </template>

      <el-table v-loading="loading" class="className" :data="informationList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column v-if="false" label="土地主键标识" align="center" prop="id" />
        <el-table-column label="土地名称" align="center" prop="lanName" />
        <el-table-column label="宗地编号" align="center" prop="parcelCode" />
        <el-table-column label="地块位置" align="center" prop="plotLocation" />
        <el-table-column label="土地面积" align="center" prop="landArea" />
        <el-table-column label="受让单位" align="center" prop="transferee" />
        <el-table-column label="土地用途" align="center" prop="landuse">
          <template #default="scope">
            <dict-tag :options="land_use" :value="scope.row.landuse" />
          </template>
        </el-table-column>
        <el-table-column label="抵押状态" align="center" prop="collateralStatus">
          <template #default="scope">
            <dict-tag :options="land_collateral_status" :value="scope.row.collateralStatus" />
          </template>
        </el-table-column>
        <el-table-column label="开发状态" align="center" prop="developmenStatus">
          <template #default="scope">
            <dict-tag :options="land_developmen_status" :value="scope.row.developmenStatus" />
          </template>
        </el-table-column>
        <el-table-column label="项目名称" align="center" prop="projectName" />
        <el-table-column label="开工日期" align="center" prop="commencementDate" width="140">
          <template #default="scope">
            <span>{{ parseTime(scope.row.commencementDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="竣工日期" align="center" prop="completionDate" width="140">
          <template #default="scope">
            <span>{{ parseTime(scope.row.completionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column width="120" label="租赁状态" align="center" prop="leaseStatus">
          <template #default="scope">
            <dict-tag :options="land_ease_status" :value="scope.row.leaseStatus" />
          </template>
        </el-table-column>
        <el-table-column label="到期提醒" align="center" prop="expireRemind" />

        <el-table-column fixed="right" width="120" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handleOpen('update', scope.row.id)"> 编辑 </el-button>
            <el-button link type="primary" @click="handleOpen('detail', scope.row.id)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改土地信息对话框 -->
    <formDialog ref="formDialogRef" @success="handleSuccess" />
  </div>
</template>

<script setup name="Information" lang="ts">
import { listInformation, getInformation, delInformation, addInformation, updateInformation } from '@/api/zichanguanli/information';
import { InformationVO, InformationQuery, InformationForm } from '@/api/zichanguanli/information/types';
import { LeaseInformationForm } from '@/api/zichanguanli/leaseInformation/types';
import { getLeaseInformation, addLeaseInformation, updateLeaseInformation } from '@/api/zichanguanli/leaseInformation';
import formDialog from './form.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { land_ease_status, land_use, land_developmen_status, land_collateral_status, land_frequency_of_rent_payments } = toRefs<any>(
  proxy?.useDict('land_ease_status', 'land_use', 'land_developmen_status', 'land_collateral_status', 'land_frequency_of_rent_payments')
);

const informationList = ref<InformationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const informationFormRef = ref<ElFormInstance>();

let initLeaseForm = ref<LeaseInformationForm>();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const detailDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const formatColumn = (row, column) => {
  // 自定义渲染函数，将 null 显示为 "-"
  return row[column.property] === null ? '-' : row[column.property];
};

const formDialogRef = ref<any>();
const handleOpen = (type: string, id?: string | number) => {
  formDialogRef.value.open(type, id);
};

const initFormData: InformationForm = {
  id: undefined,
  lanName: undefined,
  parcelCode: undefined,
  plotLocation: undefined,
  landArea: undefined,
  transferee: undefined,
  landuse: undefined,
  leaseStatus: undefined,
  collateralStatus: undefined,
  developmenStatus: undefined,
  projectName: undefined,
  commencementDate: undefined,
  completionDate: undefined,
  remarks: undefined,
  estimation: undefined,
  attachment: undefined,
  realPictures: undefined
};

const initLeaseFormData: LeaseInformationForm = {
  id: undefined,
  landInfoId: undefined,
  lessee: undefined,
  frequencyOfRentPayments: undefined,
  rents: undefined,
  associates: undefined,
  contactInformation: undefined,
  startTime: undefined,
  endTime: undefined,
  leaseTerm: undefined
};
initLeaseForm.value = { ...initLeaseFormData };
const data = reactive<PageData<InformationForm, InformationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    lanName: undefined,
    parcelCode: undefined,
    transferee: undefined,
    landuse: undefined,
    collateralStatus: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '土地主键标识不能为空', trigger: 'blur' }],
    lanName: [{ required: true, message: '土地名称不能为空', trigger: 'blur' }],
    parcelCode: [{ required: true, message: '宗地编号不能为空', trigger: 'blur' }],
    plotLocation: [{ required: true, message: '地块位置不能为空', trigger: 'blur' }],
    landArea: [{ required: true, message: '土地面积不能为空', trigger: 'blur' }],
    transferee: [{ required: true, message: '受让单位不能为空', trigger: 'blur' }],
    leaseStatus: [{ required: true, message: '租赁状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询土地信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listInformation(queryParams.value);
  informationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  initLeaseForm.value = { ...initLeaseFormData };
  informationFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: InformationVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleDetail = async (row?: InformationVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getInformation(_id);
  const resLandLease = await getLeaseInformation(_id);
  Object.assign(form.value, res.data);
  Object.assign(initLeaseForm.value, resLandLease.data);
  dialog.visible = true;
  dialog.title = '土地基础信息详情';
};

/** 删除按钮操作 */
const handleDelete = async (row?: InformationVO) => {
  const _ids = row?.id || ids.value;

  const landName = informationList.value.find((item) => item.id == _ids)?.lanName;
  await proxy?.$modal.confirm('确定删除所选的信息吗？').finally(() => (loading.value = false));
  await delInformation(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleSuccess = async (type: any) => {
  if (type === 'create') {
    await proxy?.$modal.msgSuccess('新增成功');
    await resetQuery();
  } else if (type === 'update') {
    await proxy?.$modal.msgSuccess('修改成功');
    await resetQuery();
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'zichanguanli/information/export',
    {
      ...queryParams.value
    },
    `information_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
<style scoped>
/* el-table 列数据为空自动显示 -- */
::v-deep .el-table .el-table__body td .cell:empty::after,
.el-table .el-table__body td .cell > span:empty::after,
.el-table .el-table__body td .cell .approval:empty::after,
.el-table .el-table__body td .cell div:empty::after,
.el-table .el-table__body td .cell .line-limit-length:empty::after {
  content: '-';
}
</style>
